/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package radio_GUI;


import java.util.Iterator;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import org.jdesktop.beansbinding.Binding;
import javax.swing.table.TableModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import model.DBManager;
import model.Playlist;


/**
 *
 * @author Afridis Trifon
 */
public class PlaylistForm extends javax.swing.JFrame {

    private MainMenu mainMenuRef; //A.T. metabliti jframe toy mainmenu
    private final EntityManager em; //A.T. o entity manger tis basis
    /**
     * Creates new form Playlist
     */
    public PlaylistForm(MainMenu mmRefer) {
    
        this.mainMenuRef = mmRefer; //A.T. apothikeysi refernce toy main menu
                                    //... pou mas kalese
        //this.em = mmRefer.getEm(); //DIORTHOSI to pername san param telika
                
 
       
        
        this.em = DBManager.getEm();
        
        em.getTransaction().begin();          
        em.flush();
        em.getTransaction().commit();
        //A.T.** kanoume refresh tin basi ??(debug)
        //DBManager.closeConnection();
        //DBManager.openConnection();    
        initComponents();


        //this.em = DBManager.getEm();
    
    }                                   

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        playlistQuery = java.beans.Beans.isDesignTime() ? null : DBManager.getEm().createQuery("SELECT p FROM Playlist p");
        playlistList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(playlistQuery.getResultList());
        jButtonExit = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButtonCreate = new javax.swing.JButton();
        jButtonDel = new javax.swing.JButton();
        jButtonUpdate = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        jButtonExit.setText("Πίσω");
        jButtonExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExitActionPerformed(evt);
            }
        });

        jLabel1.setText("Λίστες Τραγουδιών");

        jTable1.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, playlistList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${perigrafi}"));
        columnBinding.setColumnName("Περιγραφή");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${creationdate}"));
        columnBinding.setColumnName("Ημ/νια Δημιουργίας");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jTable1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                refreshJtable(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButtonCreate.setText("Δημιουργία");
        jButtonCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCreateActionPerformed(evt);
            }
        });

        jButtonDel.setText("Διαγραφή");
        jButtonDel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDelActionPerformed(evt);
            }
        });

        jButtonUpdate.setText("Ενημέρωση");
        jButtonUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonUpdateActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(48, 48, 48)
                .addComponent(jButtonCreate)
                .addGap(46, 46, 46)
                .addComponent(jButtonDel)
                .addGap(47, 47, 47)
                .addComponent(jButtonUpdate)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(269, 269, 269))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonExit, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(24, 24, 24))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 683, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonCreate)
                    .addComponent(jButtonDel)
                    .addComponent(jButtonUpdate))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE)
                .addComponent(jButtonExit)
                .addGap(25, 25, 25))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExitActionPerformed
       
        mainMenuRef.setVisible(true);//A.T epanefere to MainMENU 
        this.dispose(); //A.T. "katastrepse" playlist Jframe
        //A.T. console mesage....
        System.out.println("Exit Playlist Form...");
    }//GEN-LAST:event_jButtonExitActionPerformed

    private void jButtonCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCreateActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);  //A.T. "kripse" playlistForm
        //A.T. emfanise Playlist edit gia dimioyrgia playlist
        new PlaylistEdit(this).setVisible(true);
        //A.T. console mesage....
        System.out.println("Loading Edit Playlistform...");
    }//GEN-LAST:event_jButtonCreateActionPerformed

    private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
     
        //A.T. afou kanoyme observable thn list apo to Design
        //...thn ananeonoume
        playlistList.clear();
        playlistList.addAll(playlistQuery.getResultList());        
       
        System.out.println("playlist jtable refresed???!!!???");
        
    }//GEN-LAST:event_formWindowGainedFocus

    private void refreshJtable(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_refreshJtable
        // TODO add your handling code here:
        // this.jTable1.updateUI();
        //System.out.println("playlist jtable refresed???!!!???");
    }//GEN-LAST:event_refreshJtable

    private void jButtonDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDelActionPerformed
        
        //A.T. apothikeuse tin row pou einai epilegmeni sto jTable
        int row = jTable1.convertRowIndexToModel(jTable1.getSelectedRow());
        if (row>=0){//A.T. An exei epileksi row (>=0).
            //A.T. pernoume to antikimeno Playlist gia metaboli
            Playlist playListDel = playlistList.get(row);
            //A.T. emfanise Playlist edit gia digrafi playlist
            new PlaylistEdit(this ,  playListDel, true).setVisible(true);
            this.setVisible(false);  //A.T. "kripse" playlistForm
            //A.T. console mesage....
            System.out.println("Loading Edit Playlistform (DELETE)...");
        }else{
            JOptionPane.showMessageDialog(this,
                        "Πρέπει να επιλέξετε μια γραμμή απο τον πινακα");//P.A
        }
    }//GEN-LAST:event_jButtonDelActionPerformed

    private void jButtonUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonUpdateActionPerformed
        // TODO add your handling code here:
        //A.T. apothikeuse tin row pou einai epilegmeni sto jTable
        int row = jTable1.convertRowIndexToModel(jTable1.getSelectedRow());
        if (row>=0){ //A.T. An exei epileksi row (>=0).
            //A.T. pernoume to antikimeno Playlist gia metaboli
            Playlist playListModify = playlistList.get(row);
            //A.T. emfanise Playlist edit gia digrafi playlist
            new PlaylistEdit(this , playListModify, false).setVisible(true);
            this.setVisible(false);  //A.T. "kripse" playlistForm
            //A.T. console mesage....
            System.out.println("Loading Edit Playlistform (DELETE)...");
        }else{
            JOptionPane.showMessageDialog(this,
                        "Πρέπει να επιλέξετε μια γραμμή απο τον πινακα");//P.A
        }
    }//GEN-LAST:event_jButtonUpdateActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PlaylistForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PlaylistForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PlaylistForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PlaylistForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                DBManager.openConnection();//Ksekina ton entity manager
                //A.T. xriazetai null logo tou constractor
                new PlaylistForm(null).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCreate;
    private javax.swing.JButton jButtonDel;
    private javax.swing.JButton jButtonExit;
    private javax.swing.JButton jButtonUpdate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private java.util.List<model.Playlist> playlistList;
    private javax.persistence.Query playlistQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
